Updates

Recap

Basic Programming Concepts

Values and Variables

Vectors

Math operators

# basic arithmetic
2+2
## [1] 4
sum_result <- 2+2
sum_result
## [1] 4
sum_result -2
## [1] 2
4*5
## [1] 20
20/5
## [1] 4
# other common math operators and functions
4^2
## [1] 16
sqrt(4^2)
## [1] 4
log(2)
## [1] 0.6931472
exp(10)
## [1] 22026.47
log(exp(10))
## [1] 10

Loops

for-loop

# number of iterations
n <- 100
# start loop
for (i in 1:n) {

     # BODY
}

while-loop

while-loop in R

# initiate variable for logical statement
x <- 1
# start loop
while (x == 1) {

     # BODY
}

Logical statements

2+2 == 4 # is equal to
3+3 == 7
4!=7 # is not equal to
6>3 
6<7
6<=6

Control statements

Control statements in R

condition <- TRUE

if (condition) {
     print("This is true!")
} else {
     print("This is false!")
}
## [1] "This is true!"

Functions

\(f:X \rightarrow Y\)

\(2\times X = Y\)

Functions in R

  • load existing functions
# install a package
install.packages("<PACKAGE NAME>")
# load a package
library(<PACKAGE NAME>)

Functions in R

  • Write functions
myfun <- function(){
  # BODY
  
  return()
}

Functions in R

  • Example of a function: a simple power function
powerFunction <- function(base, exponent){
  
  results <- base ^ exponent
  
  return(results)
}

powerFunction(exponent = 2, base = 3)
powerFunction(base = 2, exponent = 3)
powerFunction(2, 3)
powerFunction(c(2,4,3), 3)

Going further with loops and functions: the “apply” family

numberOs <- 1

cat("Loops are s")

while (numberOs < 25) {
  cat("o")
  numberOs <- numberOs + 1
}

cat(" slow!")

Loops are soooooooooooooooooooooooo slow!

Going further with loops and functions: the “apply” family

apply applies a function to margins of an array or matrix. It loops over rows (MARGIN = 1) or columns (MARGIN = 2) of a matrix.

mymatrix <- matrix(c(1,2,3, 11,12,13, 1,10), 
                   nrow = 2, 
                   ncol = 4)
print(mymatrix)
# With a for loop
for (i in 1:ncol(mymatrix)){
  print(powerFunction(mymatrix[, i], 2))
}

# With apply
apply(mymatrix, MARGIN = 2, powerFunction, exponent = 2)

Going further with loops and functions: the “apply” family

lapply applies a function over a list (“list-” apply). It loops over each element of a list to execute a function.

mylist <- list(1,2,5,6,90)

# With a for loop
for (i in mylist){
  powerFunction(i, 2)
}

# With lapply
lapply(mylist, powerFunction, exponent = 2)

Recap

Loops

For loops apply map
Slow Fastest and reliable Allows for better syntax and elegant code
Long code Short code, based on functions Elegant integration into tidyverse
:-: :-: :-:
Exam relevant Exam relevant Not exam relevant

Tutorial: A Function to Compute the Mean

Starting point: we should be aware of how the mean is defined:

\(\bar{x} = \frac{1}{n}\left (\sum_{i=1}^n{x_i}\right ) = \frac{x_1+x_2+\cdots +x_n}{n}\).

Preparation

#####################################
# Mean Function:
# Computes the mean, given a 
# numeric vector.

Tutorial: on slow and fast sloths

Tutorial: on slow and fast sloths

We can use loops to simulate natural processes over time. Write a program that calculates the populations of two kinds of sloths over time. At the beginning of year 1, there are 1000 slow sloths and 1 fast sloth. This one fast sloth is a new mutation that comes with roller blades. Not surprisingly, being fast gives it an advantage, as it can better escape from predators.


A slow sloth

A fast sloth in its natural element

Tutorial: on slow and fast sloths

Each year, each sloth has one offspring. There are no further mutations, so slow sloths beget slow sloths, and fast sloths beget fast sloths. Also, each year 40% of all slow sloths die each year, while only 30% of the fast sloths do.

So, at the beginning of year one there are 1000 slow sloths. Another 1000 slow sloths are born. But, 40% of these 2000 slow sloths die, leaving a total of 1200 at the end of year one. Meanwhile, in the same year, we begin with 1 fast sloth, 1 more is born, and 30% of these die, leaving 1.4.

Beginning of Year Slow Sloths Fast Sloths
1 1000 1
2 1200 1.4
3 1440 1.96

Enter the first year in which the fast sloths outnumber the slow sloths.

A loop function

A loop function

Be the function

appendsums <- function(lst){
    #Repeatedly append the sum of the current last three elements 
    #of lst to lst. 
}

Create a function that repeatedly appends the sum of the current last three elements of lst to lst. To check if your function is correct, run:

sum_three = list(0, 1, 2)
appendsums(sum_three)
sum_three[10] == 230

Q&A